<template>
  <div class="createPost-container">
    <el-form
      ref="postForm"
      :model="postForm"
      :rules="rules"
      label-width="100px"
      class="form-container"
    >

      <sticky
        :z-index="10"
        :class-name="'sub-navbar '+postForm.status"
      >
        <!-- <CommentDropdown v-model="postForm.comment_disabled" /> -->
        <!-- <SourceUrlDropdown v-model="postForm.source_uri" /> -->
        <el-button
          v-loading="loading"
          style="margin-left: 10px;"
          type="success"
          @click="submitForm"
        >
          发布
        </el-button>
        <el-button
          v-loading="loading"
          type="warning"
          @click="draftForm"
        >
          存入草稿
        </el-button>
      </sticky>

      <div class="createPost-main-container">

        <el-form-item
          label="标题"
          prop="title"
        >
          <el-input v-model="postForm.title"></el-input>
        </el-form-item>

        <el-form-item
          label="作者"
          class="postInfo-container-item"
        >
          <el-input
            v-model="postForm.author"
            placeholder="输入作者"
          ></el-input>

        </el-form-item>

        <el-form-item
          label="封面:"
          class="postInfo-container-item"
        >
          <div class="img-cover-box">
            <div
              v-for="(item,index) in cover"
              class="avatar"
            >
              <span
                v-if="item.progress==100"
                class="el-upload-list__item-delete"
                @click="handleRemove(index)"
              >
                <i class="el-icon-delete"></i>
              </span>
              <img
                v-if="item.progress==100"
                :src="item.url"
                alt=""
              >
              <el-progress
                v-else
                type="circle"
                :percentage="item.progress"
              ></el-progress>

            </div>

            <el-upload
              v-if="cover.length<3"
              action="#"
              list-type="picture-card"
              :before-upload="clickUpload"
              :show-file-list="false"
            >
              <i
                slot="default"
                class="el-icon-plus"
              ></i>

            </el-upload>
          </div>

        </el-form-item>

        <el-form-item
          style="margin-bottom: 40px;"
          label="概要:"
        >
          <el-input
            v-model="postForm.conDesc"
            type="textarea"
            :autosize="{ minRows: 2, maxRows: 6 }"
            maxlength="255"
            show-word-limit
            placeholder="请输入概要"
          />

        </el-form-item>

        <el-form-item
          prop="content"
          style="margin-bottom: 30px;"
        >
          <Tinymce
            :html="postForm.content"
            ref="editor"
          />
        </el-form-item>

        <el-form-item
          prop="image_uri"
          style="margin-bottom: 30px;"
        >
          <!-- <Upload v-model="postForm.image_uri" /> -->

        </el-form-item>
      </div>
    </el-form>
  </div>
</template>

<script>
// import Tinymce from "@/components/Tinymce";
import Upload from "@/components/Upload/SingleImage3";
import MDinput from "@/components/MDinput";
import Sticky from "@/components/Sticky"; // 粘性header组件
import { validURL } from "@/utils/validate";
import { fetchArticle } from "@/api/article";
import { searchUser } from "@/api/remote-search";
import Warning from "./Warning";
import Tinymce from "@/components/WangEditor";

import {
  CommentDropdown,
  PlatformDropdown,
  SourceUrlDropdown
} from "./Dropdown";
import { createArticle } from "@/api/article";
import { client } from "@/api/qiniu";
const qiniu = client();
const defaultForm = {
  status: "draft",
  title: "", // 文章题目
  content: "", // 文章内容
  conDesc: "", // 文章摘要
  source_uri: "", // 文章外链
  image_uri: "", // 文章图片
  display_time: undefined, // 前台展示时间
  id: undefined,
  platforms: ["a-platform"],
  comment_disabled: false,
  importance: 0
};

export default {
  name: "ArticleDetail",
  components: {
    Tinymce,
    MDinput,
    Upload,
    Sticky,
    Warning,
    CommentDropdown,
    PlatformDropdown,
    SourceUrlDropdown
  },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    const validateRequire = (rule, value, callback) => {
      if (value === "") {
        this.$message({
          message: rule.field + "为必传项",
          type: "error"
        });
        callback(new Error(rule.field + "为必传项"));
      } else {
        callback();
      }
    };
    const validateSourceUri = (rule, value, callback) => {
      if (value) {
        if (validURL(value)) {
          callback();
        } else {
          this.$message({
            message: "外链url填写不正确",
            type: "error"
          });
          callback(new Error("外链url填写不正确"));
        }
      } else {
        callback();
      }
    };
    return {
      progress: 0,
      cover: [],

      postForm: Object.assign({}, defaultForm),
      loading: false,
      userListOptions: [],
      rules: {
        image_uri: [{ validator: validateRequire }],
        title: [{ validator: validateRequire }],
        content: [{ validator: validateRequire }],
        source_uri: [{ validator: validateSourceUri, trigger: "blur" }]
      },
      tempRoute: {}
    };
  },
  computed: {
    contentShortLength() {
      return this.postForm.content_short.length;
    },
    displayTime: {
      // set and get is useful when the data
      // returned by the back end api is different from the front end
      // back end return => "2013-06-25 06:59:25"
      // front end need timestamp => 1372114765000
      get() {
        return +new Date(this.postForm.display_time);
      },
      set(val) {
        this.postForm.display_time = new Date(val);
      }
    }
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id;
      this.fetchData(id);
    }

    // Why need to make a copy of this.$route here?
    // Because if you enter this page and quickly switch tag, may be in the execution of the setTagsViewTitle function, this.$route is no longer pointing to the current page
    // https://github.com/PanJiaChen/vue-element-admin/issues/1221
    this.tempRoute = Object.assign({}, this.$route);
  },
  methods: {
    handleRemove(index) {
      this.cover.splice(index, 1);
    },
    clickUpload(flie) {
      var index = this.cover.length;
      this.cover.push({
        url: "",
        progress: 0
      });
      qiniu
        .upload(flie, res => {
          this.cover[index].progress = res;
          this.cover = JSON.parse(JSON.stringify(this.cover));
        })
        .then(res => {
          this.cover[index].url = res;
          this.cover = JSON.parse(JSON.stringify(this.cover));
        });
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload(file) {
      console.log(file);
    },
    fetchData(id) {
      fetchArticle(id)
        .then(response => {
          this.postForm = response.result;
          // just for test
          // this.postForm.title += `   Article Id:${this.postForm.id}`;
          // this.postForm.content_short += `   Article Id:${this.postForm.id}`;
          this.postForm.content = this.postForm.html;
          this.$refs.editor.setHtml(this.postForm.html);
          this.cover = this.postForm.cover.split(",").map(val => {
            var data = {};
            data.url = val;
            data.progress = 100;
            return data;
          });

          // set tagsview title
          this.setTagsViewTitle();

          // set page title
          this.setPageTitle();
        })
        .catch(err => {
          console.log(err);
        });
    },
    setTagsViewTitle() {
      const title = "编辑";

      const route = Object.assign({}, this.tempRoute, {
        title: `${title}`
      });
      this.$store.dispatch("tagsView/updateVisitedView", route);
    },
    setPageTitle() {
      const title = "编辑";
      // document.title = `${title} - ${this.postForm.title}`;
    },
    submitForm() {
      console.log(this.postForm);
      this.postForm.content = this.$refs.editor.value;
      this.postForm.cover = this.cover
        .map(val => {
          return val.url;
        })
        .join(",");

      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.postForm.isSale = 1;
          this.postForm.status = "published";

          createArticle(this.postForm).then(res => {
            this.loading = true;
            this.$notify({
              title: "成功",
              message: "发布文章成功",
              type: "success",
              duration: 2000
            });
            this.loading = false;
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    draftForm() {
      if (
        this.postForm.content.length === 0 ||
        this.postForm.title.length === 0
      ) {
        this.$message({
          message: "请填写必要的标题和内容",
          type: "warning"
        });
        return;
      }

      this.postForm.status = "draft";
      this.postForm.isSale = 2;
      this.postForm.content = this.$refs.editor.value;
      this.postForm.cover = this.cover
        .map(val => {
          return val.url;
        })
        .join(",");

      createArticle(this.postForm).then(res => {
        this.$message({
          message: "保存成功",
          type: "success",
          showClose: true,
          duration: 1000
        });
      });
    },
    getRemoteUserList(query) {
      // searchUser(query).then(response => {
      //   if (!response.data.items) return;
      //   this.userListOptions = response.data.items.map(v => v.name);
      // });
    }
  }
};
</script>

<style lang="scss" scoped>
@import "~@/styles/mixin.scss";

.createPost-container {
  position: relative;

  .createPost-main-container {
    padding: 40px 45px 20px 50px;

    .postInfo-container {
      position: relative;
      @include clearfix;
      margin-bottom: 10px;

      .postInfo-container-item {
        float: left;
      }
    }
  }

  .word-counter {
    width: 40px;
    position: absolute;
    right: 10px;
    top: 0px;
  }
}

.article-textarea ::v-deep {
  textarea {
    padding-right: 40px;
    resize: none;
    border: none;
    border-radius: 0px;
    border-bottom: 1px solid #bfcbd9;
  }
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.img-cover-box {
  display: flex;
}
.img-cover-box .avatar {
  width: 148px;
  height: 148px;
  margin-right: 10px;
  display: block;
  position: relative;
}
.img-cover-box .avatar:hover .el-upload-list__item-delete {
  display: flex;
}
.img-cover-box .avatar img {
  width: 100%;
  height: 100%;
}

.el-upload-list__item-delete {
  position: absolute;
  display: none;
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background: rgba(0, 0, 0, 0.82);
  align-items: center;
  justify-content: center;
}
.el-upload-list__item-delete i {
  color: #fff;
  font-size: 30px;
  cursor: pointer;
}
</style>
